from flask import Flask, render_template,session,redirect,url_for,flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment 
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

from flask_sqlalchemy import SQLAlchemy

from flask_mail import Mail,Message

DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = '123456'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask'

SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT,
                                                                       DATABASE)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USERNAME'] = '409095380@qq.com'
app.config['MAIL_PASSWORD'] = 'cbzytwbxzaxecaia'


bootstrap = Bootstrap(app)
moment = Moment(app)   #pip install flask-moment

db = SQLAlchemy(app)
mail = Mail(app)

class NameForm(FlaskForm):
    name = StringField('What is your name?', validators=[DataRequired()])
    submit = SubmitField('Submit')

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    users = db.relationship("User", backref="role")

    def __repr__(self):
        return "<roles %r>" % self.title

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey("roles.id"))

    def __repr__(self):
        return "<roles %r>" % self.title

db.create_all()  # 会寻找所有db.Model 子类, 然后在数据库中创建对应的表; (但不会重新创建新表)

@app.shell_context_processor
def make_shell_context():
    return dict(db=db, User=User, Role=Role)

# @app.route("/")
# def hello():
#     return "Hello World!"

@app.route("/mail")
def sendMail():
    msg = Message(subject="Hello World!",
              sender="409095380@qq.com",
              recipients=["409095380@qq.com"])  #recipients为接收方
    msg.body = "This is the plain text body"
    msg.html = "This is the <b>HTML </b> body"
    with app.app_context(): 
        mail.send(msg)
    return "ok"

@app.route('/', methods=['GET', 'POST'])
def index1():
    name = None
    form = NameForm()
    if form.validate_on_submit():
        # old_name = session.get('name')
        # if old_name is not None and old_name != form.name.data:
        #     flash('Looks like you have changed your name!')

        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session["known"] = False
        else :
            session["known"] = True
        
        session["name"] = form.name.data
        form.name.data = ""
        return redirect(url_for("index1")) #对应处理url 视图函数名称
    return render_template('user.html', form=form, name=session.get("name"), known=session.get('known',False))

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

if __name__ == '__main__':
    app.debug = False
    app.run(host='localhost', port=5000)